<script lang="ts" setup>
import { ref, shallowRef } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';
import { $t } from '@vben/locales';

import { useVbenForm } from '#/adapter/form';
import { saveMaterialApi } from '#/api';
import { MaterialAttributeSelect, MaterialUnitSelect } from '#/components';
import MaterialCategoryTreeSelect from '#/components/material-category/material-category-tree-select.vue';
import MaterialSupplierSelect from '#/components/material-supplier/material-supplier-select.vue';

defineOptions({
  name: 'MaterialDrawer',
});
const selectedSupplier = ref<any[]>([]);
const selectedAttributes: any[] = [];

const [Form, formApi] = useVbenForm({
  schema: [
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'materialCode',
      label: $t('material.material.field.materialCode'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'materialName',
      label: $t('material.material.field.materialName'),
      rules: 'required',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'shortName',
      label: $t('material.material.field.shortName'),
      rules: '',
      description: '',
    },
    {
      component: shallowRef(MaterialCategoryTreeSelect),
      componentProps: {
        class: 'mr-2',
        onSelect: (value: any, option: any) => {
          formApi.setFieldValue('categoryName', option.label);
        },
      },
      fieldName: 'categoryId',
      label: $t('material.material.field.categoryName'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'model',
      label: $t('material.material.field.model'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'specification',
      label: $t('material.material.field.specification'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'brandName',
      label: $t('material.material.field.brandName'),
      rules: '',
      description: '',
    },
    {
      component: shallowRef(MaterialSupplierSelect),
      componentProps: {
        class: 'mr-2',
        initOptions: selectedSupplier,
        onSelect: (value: any, option: any) => {
          formApi.setFieldValue('manufacturerName', option.label);
        },
      },
      fieldName: 'manufacturerId',
      label: $t('material.material.field.manufacturer'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'origin',
      label: $t('material.material.field.origin'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'rawMaterial',
      label: $t('material.material.field.rawMaterial'),
      rules: '',
      description: '',
    },
    {
      component: shallowRef(MaterialAttributeSelect),
      componentProps: {
        class: 'mr-2',
        mode: 'multiple',
        onSelect: (value: any, option: any) => {
          selectedAttributes.push(`${option.value},${option.label}`);
        },
        onDeselect: (value: any, option: any) => {
          const index: any = selectedAttributes.findIndex((item) =>
            item.includes(option.value),
          );
          if (index !== -1) {
            selectedAttributes.splice(index, 1);
          }
        },
      },
      fieldName: 'skuAttributeList',
      label: $t('material.material.field.skuAttributes'),
      rules: '',
      description: '',
    },
    {
      component: 'InputNumber',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'shellLife',
      label: $t('material.material.field.shellLife'),
      rules: '',
      description: '',
    },
    {
      component: shallowRef(MaterialUnitSelect),
      componentProps: {
        class: 'mr-2',
        unitType: 'time',
        onSelect: (value: any, option: any) => {
          formApi.setFieldValue('shellLifeUnitName', option.label);
        },
      },
      fieldName: 'shellLifeUnitId',
      label: $t('material.material.field.shellLifeUnitId'),
      rules: '',
      description: '',
    },
    {
      component: 'Input',
      componentProps: {
        class: 'mr-2',
      },
      fieldName: 'remark',
      label: $t('material.material.field.remark'),
      rules: '',
      description: '',
    },
  ],
  showDefaultActions: false,
  handleSubmit: onSubmit,
  wrapperClass: 'grid-cols-2',
});

const [Drawer, drawerApi] = useVbenDrawer({
  onCancel() {
    drawerApi.close();
  },
  onConfirm: async () => {
    const { valid } = await formApi.validate();
    if (!valid) {
      return;
    }
    await formApi.submitForm();
    drawerApi.close();
  },
  onOpenChange(isOpen: boolean) {
    if (isOpen) {
      const { values, disabled } = drawerApi.getData<Record<string, any>>();
      if (values) {
        selectedSupplier.value.length = 0;
        if (values.manufacturerId && values.manufacturerName) {
          selectedSupplier.value = [
            {
              label: values.manufacturerName,
              value: values.manufacturerId,
            },
          ];
        }
        selectedAttributes.length = 0;
        if (values.skuAttributes) {
          const attrs = values.skuAttributes.split(';');
          const skuAttributeList: string[] = [];
          attrs.forEach((attr: string) => {
            const props: any[] = attr.split(',');
            selectedAttributes.push(attr);
            skuAttributeList.push(props[0]);
          });
          values.skuAttributeList = skuAttributeList;
        }
        formApi.setValues(values);
      }
      const enableEdit = !!disabled;
      formApi.setState({ commonConfig: { disabled: enableEdit } });
      drawerApi.setState({ showConfirmButton: !enableEdit });
    }
  },
  title: $t('material.material.title'),
});

async function onSubmit(values: any) {
  const rawData = drawerApi.getData().values;
  values.materialId = rawData.materialId;
  values.skuAttributeList = undefined;
  values.skuAttributes = selectedAttributes.join(';');
  await saveMaterialApi(values);
  drawerApi.setData({ success: true });
}
</script>
<template>
  <Drawer class="w-[1000px]">
    <Form />
  </Drawer>
</template>
